<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use \tpfcore\Core;
use think\Validate;
use think\Request;
class Order extends ApiBase
{
    public function getOrder($data = [])
    {
        if(!isset($data['order_sn'])){

            return [-1,"请传入订单号"];

        }

        $order = Core::loadAddonModel("Order","mall","controller")->getOrder(['where'=>['order_sn'=>$data['order_sn'],'order_status'=>0,'pay_status'=>0]]); 


        if(empty($order)){

             return [-1,"没有要支付的订单"];

        }

        $order_info = $order[0]->toArray();

        $handle=$order_info['pay_handle'];

        $code=$order_info['pay_code'];

        $handle_class="\\tpfcore\payment\\".ucfirst($handle);

        $pay_param=[
            'body'=>empty($order_info['order_info'])?"商品描述":$order_info['order_info'],        // 商品描述
            'out_trade_no'=>$data['order_sn'],                       // 商户订单号 
            'total_amount'=>$order_info['order_amount'],                    //应付款总金额
            'subject'=>"付款",                                              // 商品的标题/交易标题/订单标题/订单关键字等
            'openid'=>$data['openid']
        ];
        $result=(new $handle_class(Core::loadAddonModel("Payment","payment","controller")->getPaymentConfig($handle,$code)))->pay($pay_param,$code);
        $result['order_sn']=$data['order_sn'];

        return [0, 'success', $result];
    }

    public function createOrder($data=[]){
        $data['user_id']=1;
        $data['pay_handle']="weixin";
        // 凑订单对应的产品
        $data['order_goods']=[
            [
                'goods_price'=>$data['order_amount'],
                'goods_id'=>empty($data['id'])?1:$data['id'],
                'goods_name'=>$data['order_note']
            ]
        ];

        $result = Core::loadAddonModel("Order","mall","controller")->createOrder($data);
        
        if($result[0]==0){
            $order_sn = $result[2]['order_sn'];
            return $this->getOrder(["order_sn"=>$order_sn,"openid"=>$data['openid']]);
        }else{
            return [40040,$result[1]];
        }
    }
    // 创建实物订单
    public function createRealOrder($data=[]){
        $userInfo = $this->getBaseUserInfo();
        $data['user_id']=$userInfo['id'];

        $type = empty($data['type'])?"cart":$data['type'];

        $order_amount=0.0;  // 物品实际的总价格

        //如果是从购物车结算来的
        if($type=="cart"){
            //对应的产品
            $order_goods = Core::loadModel("Cart")->getList([
                "where"=>["user_id"=>$userInfo['id'],"is_select"=>1]
            ]);
            foreach ($order_goods as $key => $value) {
                $spec_key = $value['spec_key'];
                $price = $value['goods_price'];
                if($spec_key){
                    $arr = explode(",", $spec_key);
                    $listGoodsAttr = Core::loadModel("GoodsAttr")->getList([
                        "where"=>["id"=>["in",$arr]]
                    ]);
                    foreach ($listGoodsAttr as $k => $v) {
                        $price+=$v['attr_price'];
                    }
                    $order_goods[$key]['price']=$price;
                }
                $order_amount+=$price*$value['number'];
            }
        }else{ //直接购买
            $order_goods = Core::loadAddonModel("Goods","mall","controller")->getGoods([
                "field"=>"id,goods_sn,goods_name,goods_thumb,price,market_price",
                "where"=>["id"=>$data['goods_id']]
            ]);
            foreach ($order_goods as $key => $value) {
                $order_goods[$key]['goods_id']=$value['id'];
                $spec_key = $data['spec_key'];
                $order_goods[$key]['spec_key']=$data['spec_key'];
                $order_goods[$key]['spec_key_name']=$data['spec_key_name'];
                $order_goods[$key]['number']=$data['quantity'];
                $price = $value['price'];
                if($spec_key){
                    $arr = explode(",", $spec_key);
                    $listGoodsAttr = Core::loadModel("GoodsAttr")->getList([
                        "where"=>["id"=>["in",$arr]]
                    ]);
                    foreach ($listGoodsAttr as $k => $v) {
                        $price+=$v['attr_price'];
                    }
                    $order_goods[$key]['goods_price']=$price;
                }
                $order_amount+=$price*$data['quantity'];
            }
        }

        $data['order_amount'] = $order_amount;

        if(empty($order_goods)){
            return [40044,"没有要结算的产品"];
        }
        $data['order_goods'] = $order_goods;

        // 取物流信息
        if(!empty($data['address_id'])){
            $listAddress = Core::loadModel("UserAddress")->getList([
                "where"=>["user_id"=>$userInfo['id'],"id"=>$data['address_id']]
            ]);
            if($listAddress){
                $data['address'] = $listAddress[0]['address'];
                $data['zipcode'] = $listAddress[0]['zipcode'];
                $data['consignee'] = $listAddress[0]['consignee'];
                $data['mobile'] = $listAddress[0]['mobile'];
            }
        }

        $result = Core::loadAddonModel("Order","mall","controller")->createOrder($data);
        
        if($result[0]==0){
            // 清空购物车
            if($type=="cart"){
                $res = Core::loadModel("Cart")->deleteObject(["user_id"=>$userInfo['id'],"is_select"=>1],true);    
                if(!$res){
                    return [40045,"操作失败"];
                }
            }
            $order_sn = $result[2]['order_sn'];
            return $this->getOrder(["order_sn"=>$order_sn,"openid"=>$data['openid']]);
            
        }else{
            return [40040,$result[1]];
        }

    }
    public function payOrder($data=[]){
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('mini_wechat_payOrder')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError()];
        }
        return $this->getOrder(["order_sn"=>$data['order_sn'],"openid"=>$data['openid']]);
    }
    /*
        微信创建订单有很多的场景，根据不同场景进行相应的处理
    */
    public function creatWechateOrder($data=[]){
        if(empty($data['scene'])) return [-1,"请指定下单场景"];
        $userinfo = $this->getBaseUserInfo();
        $data['user_id']=empty($userinfo)?0:$userinfo['id'];
        $data['pay_handle']="weixin";
        $data['pay_code']=empty($data['pay_code'])?"mp":$data['pay_code'];
        // 凑订单对应的产品
        $data['order_goods']=[
            [
                'goods_price'=>$data['order_amount'],
                'goods_id'=>empty($data['id'])?0:$data['id']
            ]
        ];

        switch ($data['scene']) {
            case 'pay_to_business':     //线下扫描付款
                $data['order_goods'][0]['goods_name']="线下支付";
                break;
            case 'recharge':            //充值
                $data['order_goods'][0]['goods_name']="用户充值";
                break;
            
            default:
                # code...
                break;
        }

        $result = Core::loadAddonModel("Order","mall","controller")->createOrder($data);
        if($result[0]==0){
            return [0,"success",$result[2]['order_sn']];
        }else{
            return [40040,$result[1]];
        }
    }
    public function orderWechatList($data=[]){
        $userinfo = $this->getBaseUserInfo();
        $user_id=empty($userinfo)?0:$userinfo['id'];

        $where = ["__ORDER__.user_id"=>$user_id,"__ORDER__.is_delete"=>0];
        switch ($data['status']) {
            case 2:
                $where['__ORDER__.order_status'] =4;
                $where["__ORDER__.shipping_status"] = 3;
                break;
            case 3:
                $where['__ORDER__.order_status'] =2;
                break;
            case 4:
                $where['__ORDER__.order_status'] =0;
                break;
            case 5:
                $where['__ORDER__.order_status'] =3;
                $where['__ORDER__.shipping_status'] =3;
                $where['__ORDER__.pay_status'] =1;
                break;
            default:
                # code...
                break;
        }

        $result = Core::loadAddonModel("Order","mall","controller")->getOrder([
            "where"=>$where,
            "field"=>"__ORDER__.*,__SELLER__.seller_name,__SELLER__.thumb,__SELLER__.address",
            'join'=>['join'=>"__SELLER__",'condition'=>"__ORDER__.seller_id=__SELLER__.id","type"=>"left"
            ],
            'order'=>"__ORDER__.add_time desc",
            "paginate"  =>['rows' => DB_LIST_ROWS],
        ]);
        return [0,"success",$result];
    }
    /*
    2:待付款
    3:待发货
    4:待收货
    5:待评价
    */
    public function orderList($data=[]){
        $userinfo = $this->getBaseUserInfo();
        $user_id=empty($userinfo)?0:$userinfo['id'];
        $limit=empty($data['limit'])?DB_LIST_ROWS:$data['limit'];

        $where = ["__ORDER__.user_id"=>$user_id,"__ORDER__.is_delete"=>0];
        switch ($data['status']) {
            case 2:
                $where['__ORDER__.order_status'] =0;
                $where["__ORDER__.pay_status"] = 0;
                break;
            case 3:
                $where['__ORDER__.order_status'] =1;
                $where['__ORDER__.pay_status'] =1;
                $where['__ORDER__.shipping_status'] =1;
                break;
            case 4:
                $where['__ORDER__.order_status'] =3;
                $where['__ORDER__.pay_status'] =2;
                $where['__ORDER__.shipping_status'] =2;
                break;
            case 5:
                $where['__ORDER__.order_status'] =4;
                $where['__ORDER__.shipping_status'] =3;
                $where['__ORDER__.pay_status'] =1;
                $where['__ORDER__.has_comment'] =0;
                break;
            default:
                # code...
                break;
        }

        $result = $user_id?Core::loadAddonModel("Order","mall","controller")->getOrder([
            "where"=>$where,
            "field"=>"__ORDER__.id,__ORDER__.order_sn,__ORDER__.order_status,__ORDER__.shipping_status,__ORDER__.pay_status,__ORDER__.order_amount,__ORDER__.user_note,__ORDER__.has_comment",
            'order'=>"__ORDER__.add_time desc",
            "paginate"  =>['rows' => $limit],
        ]):[];

        $orderGoodsModel=Core::loadAddonModel("OrderGoods","mall","controller");

        foreach ($result as $key => $value) {
            $order_id = $value['id'];
            $result[$key]['order_goods'] = $orderGoodsModel->getOrderGoods(["where"=>["order_id"=>$order_id],"field"=>"goods_id,goods_name,goods_thumb,number,goods_price,spec_key_name"]);
        }

        return [0,"success",$result];
    }
    public function saveGoodsComment($data){
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('saveGoodsComment')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }

        $orderInfo = self::getOneObject(['order_sn'=>$data['order_sn']],"id,order_sn,seller_id,order_status");
        if($orderInfo['order_status']==4){ return [40001,"已评论"];}

        $member_id = $this->getBaseUserInfo();
        $data['user_id'] = $member_id['id'];
        $data['username'] = $member_id['nickname'];
        $data['goods_id'] = $orderInfo['seller_id'];
        $data['order_id'] = $orderInfo['id'];
        $data['ip'] = request()->ip();
        $data['add_time'] = time();

        $last_id=Core::loadModel("GoodsComment")->saveObject($data);
        if($last_id){
            self::saveObject(['id'=>$orderInfo['id'],'order_sn'=>$data['order_sn'],'order_status'=>4]);
            return [0,"评价成功"];
        }else {
            return [40001,"网络错误"];
        }
    }
    public function cancelOrder($data=[]){
        $member_info = $this->getBaseUserInfo();
        $user_id=$member_info['id'];
        $result = self::updateObject(["order_sn"=>$data['order_sn'],"user_id"=>$user_id],["order_status"=>2,"pay_status"=>4]);
        if($result){
            return [0,"success"];
        }else{
            return [40045,"操作失败"];
        }
    }
    public function deleteOrder($data=[]){
        $member_info = $this->getBaseUserInfo();
        $user_id=$member_info['id'];
        $result = self::deleteObject(["order_sn"=>$data['order_sn'],"user_id"=>$user_id,"order_status"=>2,"pay_status"=>4],false,"is_delete");
        if($result){
            return [0,"success"];
        }else{
            return [40045,"操作失败"];
        }
    }
    public function remindShip($data=[]){
        $member_info = $this->getBaseUserInfo();
        $user_id=$member_info['id'];
        $result = self::updateObject(["order_sn"=>$data['order_sn'],"user_id"=>$user_id,"order_status"=>1,"shipping_status"=>1,"pay_status"=>1],["remind_ship_time"=>time()]);
        if($result){
            return [0,"success"];
        }else{
            return [40045,"操作失败"];
        }
    }
    public function getOrderInfo($data=[]){
        $result = self::getList([
            "field"=>"id,order_note,address,consignee,mobile,shipping_name,shipping_code",
            "where"=>["order_sn"=>$data['order_sn'],"order_status"=>3,"pay_status"=>1]
        ]);
        
        if($result){
            if(isset($data['ext']) && $data['ext']=="get_ship_info"){       // 获取物流详细信息
                $ship = Core::loadModel("AliyunSdk","","logic")->getExpress($result[0]['shipping_code']);
                $result[0]['ship']=$ship;
            }
            if(isset($data['ext']) && $data['ext']=="get_order_info"){      // 获取订单详情
                $orderGoodsModel=Core::loadAddonModel("OrderGoods","mall","controller");
                $order_id=$result[0]['id'];
                $result[0]['order_goods'] = $orderGoodsModel->getOrderGoods(["where"=>["order_id"=>$order_id],"field"=>"goods_id,goods_name,goods_thumb,number,goods_price,spec_key_name"]);
            }
            return [0,"success",$result[0]];
        }else{
            return [40045,"操作失败"];
        }
    }
}